<template>
  <div class="risk-assessment-management-start">
    <card class="card" :isCustomHeader="true" :isCustomFooter="true">
      <template #header>
        <t-breadcrumb maxItemWidth="150">
          <t-breadcrumbItem @click="$router.replace('/risk-assessment/management')">评估管理</t-breadcrumbItem>
          <t-breadcrumbItem>启动评估</t-breadcrumbItem>
        </t-breadcrumb>
      </template>
      <template>
        <t-steps v-model="stepsCurrent" readonly :options="stepsOptions" />
        <t-divider />
      </template>
      <template v-if="stepsCurrent === PAGE_STATUS.CHOOSE">
        <p style="margin-bottom: 20px">请选择需要使用的评估模板：</p>
        <evaluation-template
          class="evaluation-template"
          v-model="chooseTemplate"
          :records="templateArray"
          :isNeedChoose="true"
        />
      </template>
      <template v-if="stepsCurrent === PAGE_STATUS.INFOMATION">
        <start-information ref="startInformation" :qsInformation="qsInformation" :chooseTemplate="chooseTemplate" />
      </template>
      <template v-if="stepsCurrent === PAGE_STATUS.ALLOCATION">
        <start-allocation :qsInformation="qsInformation" :userArr="userArr" />
      </template>
      <template #footer>
        <t-row justify="space-between">
          <div>
            <t-button
              v-if="stepsCurrent === PAGE_STATUS.INFOMATION || stepsCurrent === PAGE_STATUS.ALLOCATION"
              :disabled="stepsCurrent === PAGE_STATUS.INFOMATION && qsInformation.id !== undefined"
              @click="preStep"
            >
              上一步
            </t-button>
          </div>
          <t-space>
            <t-button theme="default" @click="$router.replace('/risk-assessment/management')">取消</t-button>
            <t-button v-if="stepsCurrent !== PAGE_STATUS.ALLOCATION" @click="nextStep">下一步</t-button>
            <t-button v-if="stepsCurrent === PAGE_STATUS.ALLOCATION" @click="submitData">提交</t-button>
          </t-space>
        </t-row>
      </template>
    </card>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import Card from '@/components/Card/index.vue';
import EvaluationTemplate from '@/components/EvaluationTemplate/index.vue';
import StartInformation from './components/StartInformation.vue';
import StartAllocation from './components/StartAllocation.vue';
import { PAGE_STATUS, stepsOptions } from '@/constants/risk-assessment-management';

import { getAllQsTemplate, queryMultipleTemplate } from '@/service/risk-assessment/template';
import { requestUserByOrg } from '@/service/business-management/role';
import { requestSaveQsList, requestQsList } from '@/service/risk-assessment/management';
import { setLocalStorage, getLocalStorage } from '@/utils/storage';
import { processSurveyQuestion, generateAnswerArray } from './utils/common';
import { MessagePlugin } from 'tdesign-vue';

export default {
  name: 'riskAssessmentManagementStart',
  components: { Card, EvaluationTemplate, StartInformation, StartAllocation },
  data() {
    return {
      // 页面状态
      // CHOOSE: 1, 选择模块
      // INFOMATION: 2, 评估信息
      // ALLOCATION: 3, 评估职能分配
      PAGE_STATUS,
      // 步骤条配置项
      stepsOptions,
      // 当前步骤
      stepsCurrent: PAGE_STATUS.CHOOSE,
      // 模板列表数组
      templateArray: [],

      // 当前选择的模板
      chooseTemplate: [],
      // 当前分配填写人和审核人的用户列表
      userArr: [],
      // 评估信息对象
      qsInformation: {
        answer: {},
        answerId: undefined,
        comments: '',
        name: '',
        question: {},
        reviewId: undefined,
        stopDate: undefined,
        // 每一页作答人和问题name数组
        qsDetailList: [],
      },
    };
  },
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      Promise.all([requestQsList(id), requestUserByOrg()]).then((res) => {
        if (!res[0] || !res[1]) return;

        let answerArr = getLocalStorage(`questionnaire-qsDetailList-${id}`);
        if (!answerArr) answerArr = generateAnswerArray(res[0].question?.pages);
        // eslint-disable-next-line prefer-destructuring
        res[0].qsDetailList = answerArr;
        this.$set(this, 'qsInformation', res[0]);
        this.userArr = res[1].map((item) => ({ label: item.name, value: item.id }));
        this.chooseTemplate = res[0].qsTemplate?.map((item) => {
          const id = Object.keys(item)[0];
          return { value: id, label: item[id] };
        });
        this.stepsCurrent = PAGE_STATUS.INFOMATION;
      });
      return;
    }
    this.fetchData();
  },
  methods: {
    // 初始化数据，请求所有模板
    fetchData() {
      getAllQsTemplate().then((res) => {
        this.templateArray = res;
      });
    },
    // 执行上一步操作
    preStep() {
      if (this.stepsCurrent === PAGE_STATUS.INFOMATION) this.stepsCurrent = PAGE_STATUS.CHOOSE;
      else if (this.stepsCurrent === PAGE_STATUS.ALLOCATION) this.stepsCurrent = PAGE_STATUS.INFOMATION;
    },
    // 执行下一步操作
    nextStep() {
      if (this.stepsCurrent === PAGE_STATUS.CHOOSE) {
        if (this.chooseTemplate.length === 0) {
          MessagePlugin.error('请选择模板以执行下一步！');
          return;
        }
        const ids = this.chooseTemplate.map((_) => _.value);
        Promise.all([queryMultipleTemplate(ids.join(',')), requestUserByOrg()]).then((res) => {
          if (!res[0] || !res[1]) return;
          const { questionArr, answerArr, riskArr } = processSurveyQuestion(res[0]);
          this.qsInformation.qsDetailList = answerArr;
          this.qsInformation.riskDTOs = riskArr;
          this.qsInformation.question = {
            pages: questionArr,
          };
          this.userArr = res[1].map((item) => ({ label: item.name, value: item.id }));
          this.stepsCurrent = PAGE_STATUS.INFOMATION;
        });
      } else if (this.stepsCurrent === PAGE_STATUS.INFOMATION) {
        this.$refs.startInformation.$refs.form.validate().then((res) => {
          if (res === true) {
            this.stepsCurrent = PAGE_STATUS.ALLOCATION;
          }
        });
      }
    },
    // 提交数据
    submitData() {
      if (!this.qsInformation.answerId || !this.qsInformation.reviewId) {
        this.$message.error('请分配任务后再进行提交');
        return;
      }

      this.qsInformation.qsTemplateId = this.chooseTemplate.map((item) => item.value).join(',');
      this.qsInformation.stopDate = dayjs(this.qsInformation.stopDate).hour(23).minute(59).second(59).format('YYYY-MM-DD HH:mm:ss')
      if (this.qsInformation.answerId === '-') {
        this.qsInformation.answerId = undefined;
      }

      requestSaveQsList(this.qsInformation).then((res) => {
        if (!res || res.isError) return;
        MessagePlugin.success('添加评估成功');
        setLocalStorage(`questionnaire-qsDetailList-${res.data}`, this.qsInformation.qsDetailList);
        this.$router.replace({ path: '/risk-assessment/management/answer', query: { id: res.data } });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.risk-assessment-management-start {
  .card {
    /deep/ .t-card__footer {
      border-top: 1px solid var(--td-component-border);
    }
  }
}
</style>
